package com.slkj.shilixiaoyuanapp.ui.main;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.slkj.shilixiaoyuanapp.R;
import com.slkj.shilixiaoyuanapp.base.LazyFragment;
import com.slkj.shilixiaoyuanapp.data.UserRequest;
import com.slkj.shilixiaoyuanapp.entity.UserEntity;
import com.slkj.shilixiaoyuanapp.entity.parent.ChangeRoleEntity;
import com.slkj.shilixiaoyuanapp.net.CommonResult;
import com.slkj.shilixiaoyuanapp.net.HttpHeper;
import com.slkj.shilixiaoyuanapp.net.callback.BaseFunctionCallBack;
import com.slkj.shilixiaoyuanapp.net.callback.CommonCallBack;
import com.slkj.shilixiaoyuanapp.ui.parent.mine.StudentInfoActivity__JumpCenter;
import com.slkj.shilixiaoyuanapp.ui.user.activity.ChangeNickNameActivity;
import com.slkj.shilixiaoyuanapp.ui.user.activity.MyCollectionsActivity;
import com.slkj.shilixiaoyuanapp.ui.user.activity.MyFilesActivity;
import com.slkj.shilixiaoyuanapp.ui.user.activity.PersonalInformationActivity;
import com.slkj.shilixiaoyuanapp.ui.user.activity.SetUpActivity;
import com.slkj.shilixiaoyuanapp.ui.user.activity.StudentsCheckActivity;
import com.slkj.shilixiaoyuanapp.ui.user.activity.StudentsCheckActivity__JumpCenter;
import com.slkj.shilixiaoyuanapp.ui.user.adapter.PersonHeadAdapter;
import com.slkj.shilixiaoyuanapp.util.StringUtils;
import com.slkj.shilixiaoyuanapp.util.UpdataFileUtil;
import com.slkj.shilixiaoyuanapp.util.picture.TakePictureUtils;
import com.slkj.shilixiaoyuanapp.view.DialogProvider;
import com.slkj.shilixiaoyuanapp.view.dialog.LoadSuccessAndFailDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.ObservableSource;

/**
 * Created  on 2018-07-15
 *
 * @author 唐开阔
 * @describe 首页我的fragment
 */
public class ParentsMyFragment extends LazyFragment implements View.OnClickListener, BaseQuickAdapter.OnItemClickListener {
    @BindView(R.id.layout_personal_name)
    LinearLayout layoutName;
    @BindView(R.id.tv_nickname)
    TextView tv_nickname;
    @BindView(R.id.iv_set_name)
    ImageView setName;
    @BindView(R.id.my_head_recyclerview)
    RecyclerView recyclerView;
    @BindView(R.id.layout_personal_information)
    LinearLayout personalInformation;
    @BindView(R.id.layout_students_check)
    LinearLayout studentsCheck;
    @BindView(R.id.layout_my_file)
    LinearLayout myFile;
    @BindView(R.id.layout_my_collection)
    LinearLayout myCollection;
    @BindView(R.id.layout_set_up)
    LinearLayout setUp;
//    @BindView(R.id.layout_set_name_status)
//    LinearLayout nameStatus;
    @BindView(R.id.tv_set_name_cancel)
    TextView cancel;
    @BindView(R.id.tv_set_name_sure)
    TextView sure;
    @BindView(R.id.ll_changeto_teacher)
    LinearLayout changeteach;
    @BindView(R.id.civ_head)
    CircleImageView civ_head;
    int schoolId;
    int childId;
    public TakePictureUtils takePictureUtils;


    private List<UserEntity.StudentEntity> list = new ArrayList<>();
    private PersonHeadAdapter adapter;
    @Override
    protected int getResId() {
        return R.layout.parents_my_fragment;
    }

    @Override
    protected void onRealLoaded() {
        for (int i=0;i<UserRequest.getInstance().getUser().getStudents().size();i++){
            if (UserRequest.getInstance().getUser().getStudents().get(i).getIsSelect()==1){
                schoolId=UserRequest.getInstance().getUser().getStudents().get(i).getSchoolId();
                childId=UserRequest.getInstance().getUser().getStudents().get(i).getId();
            }
        }
        if (UserRequest.getInstance().getUser().getRoles().size()==2){
            if (UserRequest.getInstance().getUser().getRoles().contains(1)&&UserRequest.getInstance().getUser().getRoles().contains(2)){
                changeteach.setVisibility(View.VISIBLE);
            }
        }
        Glide.with(getContext()).load(UserRequest.getInstance().getUser().getUser().getHeadImg()).asBitmap().centerCrop().error(R.drawable.ic_man).placeholder(R.drawable.ic_man).into(civ_head);
        tv_nickname.setText(UserRequest.getInstance().getUser().getUser().getUNickName());
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL,false));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setNestedScrollingEnabled(false);
        if (UserRequest.getInstance().getUser().getStudents()!=null) {
            list.addAll(UserRequest.getInstance().getUser().getStudents());
        }
        adapter = new PersonHeadAdapter(list,getActivity());
        recyclerView.setAdapter(adapter);
        initListener();
    }

    private void initListener() {
        personalInformation.setOnClickListener(this);
        studentsCheck.setOnClickListener(this);
        myFile.setOnClickListener(this);
        myCollection.setOnClickListener(this);
        setUp.setOnClickListener(this);
        adapter.setOnItemClickListener(this);
        setName.setOnClickListener(this);
        //tv_nickname.setText("王麻子的家长");
        cancel.setOnClickListener(this);
        sure.setOnClickListener(this);
        changeteach.setOnClickListener(this);
        civ_head.setOnClickListener(this);
        setName.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        if (v==civ_head){
            //startActivity(PersonalInformationActivity.class);
            takePictureUtils = TakePictureUtils.Builder.from(this).isCompressor(false).isTailor(false).creat();
            takePictureUtils.setTakeCallBacklistener(new TakePictureUtils.TakePictureListener() {
                @Override
                public void successful(File outFile) {

                    upNewHead(outFile.getPath());
                }

                @Override
                public void failed(int errorCode, List<String> deniedPermissions) {
                }
            });
            showPhotoDialog();
        }
        if (v==setName){
            startActivity(ChangeNickNameActivity.class);
        }
        if (v == setName){
            tv_nickname.setFocusableInTouchMode(true);
            tv_nickname.setFocusable(true);
            tv_nickname.requestFocus();
            //nameStatus.setVisibility(View.VISIBLE);
        }
        if (v == cancel){
            //tv_nickname.setText("王麻子的家长");
            tv_nickname.setFocusableInTouchMode(false);
            tv_nickname.setFocusable(false);
            //nameStatus.setVisibility(View.GONE);
        }
        if (v == sure){
            tv_nickname.setFocusableInTouchMode(false);
            tv_nickname.setFocusable(false);
            //nameStatus.setVisibility(View.GONE);
        }
        if (v == personalInformation){
            //个人信息
            //startActivity(PersonalInformationActivity.class);
            StudentInfoActivity__JumpCenter.builder(getContext()).setStuId(childId).create().go();
        }
        if (v == studentsCheck){
            //学生考勤
            //startActivity(StudentsCheckActivity.class);
            StudentsCheckActivity__JumpCenter.builder(getContext()).setStuId(childId).create().go();
        }
        if (v == myFile){
            //我的文件
            startActivity(MyFilesActivity.class);
        }
        if (v == myCollection){
            //我的收藏
            startActivity(MyCollectionsActivity.class);
        }
        if (v == setUp){
            //设置
            startActivity(SetUpActivity.class);
        }
        if (v==changeteach){
            UserRequest.getInstance().getUser().setExtraDatasourse(UserRequest.getInstance().getUser().getDatasource());
            HttpHeper.get().parentService().changeUser(schoolId,childId,UserRequest.getInstance().getUser().getDefaultRole()).compose(getThread())
                    .compose(bindToLifecycle())
                    .subscribe(new CommonCallBack<ChangeRoleEntity>(true, getContext()) {
                        @Override
                        public void onCallBackSuccess(ChangeRoleEntity data) {
                            UserEntity userEntity = UserRequest.getInstance().getUser();
                            userEntity.setDefaultRole(2);
                            userEntity.getUser().setId(data.getUserId());
                            userEntity.setDatasource(userEntity.getExtraDatasourse());
                            UserRequest.getInstance().setUser(userEntity);
                            getActivity().finish();
                            Intent intent = new Intent(getContext(), MainActivity.class);
                            startActivity(intent);
                            getActivity().overridePendingTransition(0, 0);

                        }
                    });
        }

    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        UserEntity.StudentEntity personCenterEntity = list.get(position);
        if (personCenterEntity.getIsSelect()==1) {
            //showToast("当前为"+personCenterEntity.getName());
//            personCenterEntity.setChoose(!personCenterEntity.isChoose());
            //StudentInfoActivity__JumpCenter.builder(getContext()).setStuId(childId).create().go();
        }else {
            HttpHeper.get().parentService().changeUser(personCenterEntity.getSchoolId(),personCenterEntity.getId(),UserRequest.getInstance().getUser().getDefaultRole()).compose(getThread())
                    .compose(bindToLifecycle())
                    .subscribe(new CommonCallBack<ChangeRoleEntity>(true, getContext()) {
                        @Override
                        public void onCallBackSuccess(ChangeRoleEntity data) {
                            for (int i = 0; i < list.size(); i++) {
                                if (i!=position) {
                                    list.get(i).setIsSelect(0);
                                }
                            }
                            UserRequest.getInstance().getUser().getUser().setId(data.getUserId());
                            personCenterEntity.setIsSelect(1);
                            UserRequest.getInstance().getUser().setDatasource(personCenterEntity.getDatasource());
                            adapter.notifyDataSetChanged();
                            childId=personCenterEntity.getId();
                        }
                    });
//            for (int i = 0; i < list.size(); i++) {
//                if (i!=position) {
//                    list.get(i).setIsSelect(0);
//                }
//            }
//            personCenterEntity.setIsSelect(1);
        }
        adapter.notifyDataSetChanged();
    }

    /**
     * 上传新头像
     *
     * @param path
     */
    private void upNewHead(String path) {
        List<String> picPaths = new ArrayList<>();
        picPaths.add(path);
        UpdataFileUtil.UpImgObservable("head", picPaths)
                .flatMap(new BaseFunctionCallBack<List<String>, String>() {
                    @Override
                    public ObservableSource<CommonResult<String>> back(List<String> result) {
                        return HttpHeper.get().userService().updateHeadImg(StringUtils.listToString(result));
                    }
                })
                .compose(getThread())
                .compose(bindToLifecycle())
                .subscribe(new CommonCallBack<String>(true,getContext()) {
                    @Override
                    public void onCallBackSuccess(String data) {
                        Glide.with(ParentsMyFragment.this).load(data).into(civ_head);
                        LoadSuccessAndFailDialog.showSuccess(getContext(),data);
                        UserEntity userEntity = UserRequest.getInstance().getUser();
                        userEntity.getUser().setHeadImg(data);
                        UserRequest.getInstance().setUser(userEntity);
                    }
                });
    }

    public void showPhotoDialog() {
        DialogProvider.getPhotoDialog(getContext(), new DialogProvider.TakePicTypeListener() {
            @Override
            public void takePhoto() {
                takePictureUtils.getByCarema();
            }
            @Override
            public void chosePhoto() {
                takePictureUtils.getByAlbum();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        takePictureUtils.attachToActivityForResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        takePictureUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}